<template>
  <div 
    :class="[
      'rounded-full overflow-hidden flex items-center justify-center',
      sizeClasses,
      className
    ]"
  >
    <img
      v-if="avatar"
      :src="getImageUrl(avatar)"
      :alt="nickname || '用户头像'"
      class="w-full h-full object-cover"
      @error="handleImageError"
    />
    <div
      v-else
      class="w-full h-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white font-bold"
      :class="textSizeClass"
    >
      {{ initial }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'

const props = defineProps<{
  avatar?: string | null
  nickname?: string | null
  size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'
  className?: string
}>()

const { getImageUrl } = useImageUrl()
const imageError = ref(false)

// 获取首字母
const initial = computed(() => {
  return props.nickname?.charAt(0).toUpperCase() || 'U'
})

// 尺寸样式
const sizeClasses = computed(() => {
  const sizes = {
    xs: 'w-6 h-6',
    sm: 'w-8 h-8',
    md: 'w-10 h-10',
    lg: 'w-16 h-16',
    xl: 'w-20 h-20',
    '2xl': 'w-24 h-24',
  }
  return sizes[props.size || 'md']
})

// 文字尺寸
const textSizeClass = computed(() => {
  const sizes = {
    xs: 'text-xs',
    sm: 'text-sm',
    md: 'text-base',
    lg: 'text-2xl',
    xl: 'text-3xl',
    '2xl': 'text-4xl',
  }
  return sizes[props.size || 'md']
})

// 图片加载错误处理
const handleImageError = () => {
  imageError.value = true
}
</script>

